package com.dic.activity;

import com.dic.R;
import com.dic.model.Dic;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class DicDetailActivity extends Activity {

	private Dic dicData;
	private TextView word;
	private TextView explain;
	private CheckBox ismark;
	private SQLiteDatabase database;
	private final String DATABASE_PATH = "/data/data/com.dic/databases/";
	private final String DATABASE_FILENAME = "english.db3";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.word_detail_view);

		Intent intent = getIntent();
		dicData = (Dic) intent.getSerializableExtra("dic");
		word = (TextView) findViewById(R.id.tv_word);
		explain = (TextView) findViewById(R.id.tv_explain);

		ismark = (CheckBox) findViewById(R.id.cb_ismark);

		word.setText(dicData.getWord());
		explain.setText(dicData.getExplain());

		if (dicData.getMark() == 0) {
			ismark.setChecked(false);
		} else {
			ismark.setChecked(true);
		}

		ismark.setOnCheckedChangeListener(new checkchange());

	}

	private class checkchange implements OnCheckedChangeListener {
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if (isChecked) {
				// add
				dicData.setMark(1);
				Toast.makeText(DicDetailActivity.this, R.string.checkaddbook, Toast.LENGTH_SHORT).show();

			} else {
				// delete
				dicData.setMark(0);
				Toast.makeText(DicDetailActivity.this, R.string.checkdelbook, Toast.LENGTH_SHORT).show();
			}
			changebookmark();
		}

	}

	private void changebookmark() {
		if (database == null || !database.isOpen()) {
			database = SQLiteDatabase.openOrCreateDatabase(DATABASE_PATH + DATABASE_FILENAME, null);

		}
		String[] id = { String.valueOf(dicData.getId()) };
		ContentValues cv = new ContentValues();
		cv.put("bookmark", dicData.getMark());
		database.update("ENGLISH", cv, "id=?", id);
		database.close();

	}

}
